package com.pokermind.dse.tcp.handler;

import com.pokermind.dse.tcp.config.TcpServerConfig;
import com.pokermind.dse.tcp.protocol.ProtocolDecoder;
import com.pokermind.dse.tcp.protocol.ProtocolEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Server Channel Initializer
 * 服务器通道初始化器，配置Netty处理链
 * 
 * Pipeline配置：
 * 1. IdleStateHandler - 空闲连接检测
 * 2. ProtocolDecoder - 协议解码器
 * 3. ProtocolEncoder - 协议编码器  
 * 4. ConnectionHandler - 连接管理
 * 5. BusinessHandler - 业务处理
 * 
 * @author PokerMind Team
 */
@Component
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger logger = LoggerFactory.getLogger(ServerChannelInitializer.class);

    @Autowired
    private TcpServerConfig config;

    @Autowired
    private ConnectionHandler connectionHandler;

    @Autowired  
    private BusinessHandler businessHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 1. 空闲连接检测 (读超时, 写超时, 读写超时)
        if (config.getProtocol().getReadTimeout() > 0 || config.getProtocol().getWriteTimeout() > 0) {
            pipeline.addLast("idleStateHandler", new IdleStateHandler(
                    config.getProtocol().getReadTimeout(),   // 读空闲时间
                    config.getProtocol().getWriteTimeout(),  // 写空闲时间  
                    0,                                        // 读写空闲时间
                    TimeUnit.SECONDS));
        }

        // 2. 协议编解码器
        pipeline.addLast("protocolDecoder", new ProtocolDecoder());
        pipeline.addLast("protocolEncoder", new ProtocolEncoder());

        // 3. 连接管理器
        pipeline.addLast("connectionHandler", connectionHandler);

        // 4. 业务处理器
        pipeline.addLast("businessHandler", businessHandler);

        if (logger.isDebugEnabled()) {
            logger.debug("Channel pipeline initialized for: {}", ch.remoteAddress());
        }
    }

    @Override
    public void exceptionCaught(io.netty.channel.ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("Error in channel initializer for {}: {}", 
                ctx.channel().remoteAddress(), cause.getMessage(), cause);
        ctx.close();
    }
}
